import { StageTypes } from "./types/StageTypes";
import { Container } from "./Container";
import { BaseLayer } from "./BaseLayer";

// 事件名称
const EVENTS = ["mousedown", "mousemove", "mouseup"];

export class Stage extends Container<BaseLayer> {
  content: HTMLDivElement;
  _pointerPosition: any;
  constructor(types: StageTypes) {
    super(types);
    this._buildDOM();
    this._bindContentEvents();
  }

  // 创建canvas外部div
  _buildDOM() {
    let container = this.container() as HTMLElement;
    if (typeof container === "string") {
      container = document.getElementById("container") as HTMLElement;
    }

    container.innerHTML = "";

    this.content = document.createElement("div");
    this.content.style.position = "relative";
    this.content.style.userSelect = "none";

    container.appendChild(this.content);
  }

  // 添加监听事件
  _addEvent(ctx, eventName) {
    this.content.addEventListener(
      eventName,
      (evt) => {
        ctx[`_${eventName}`](evt);
      },
      false
    );
  }
  // 初始化事件监听
  _bindContentEvents() {
    for (let i = 0; i < EVENTS.length; i++) {
      const eventName = EVENTS[i];
      this._addEvent(this, eventName);
    }
  }
  // 鼠标按下
  _mousedown(evt) {
    this.setPointersPositions(evt);
    let shape = this.getIntersection(this.getPointerPosition());
    if (shape) {
      shape._fireAndBubble("mousedown", { evt });
    }
  }

  // 鼠标滑过
  _mousemove(evt) {
    this.setPointersPositions(evt);
    let shape = this.getIntersection(this.getPointerPosition());
    if (shape) {
      shape._fireAndBubble("mousemove", { evt });
    }
  }

  // 鼠标弹起
  _mouseup(evt) {
    this.setPointersPositions(evt);
    let shape = this.getIntersection(this.getPointerPosition());
    if (shape) {
      shape._fireAndBubble("mouseup", { evt });
    }
  }

  // 容器
  container() {
    return this.attrs.container;
  }
  // 添加图层
  add(layer) {
    super.add(layer);
    layer._setCanvasSize(this.getWidth(), this.getheight());
    layer.draw();
    this.content.appendChild(layer.canvas);
    return this;
  }
  // 设置当前鼠标位置
  setPointersPositions(evt) {
    const rect = this.content.getBoundingClientRect();
    this._pointerPosition = {
      left: evt.clientX - rect.left,
      top: evt.clientY - rect.top,
    };
  }
  // 获取当前鼠标位置
  getPointerPosition() {
    return this._pointerPosition;
  }

  getIntersection(pos) {
    if (!pos) {
      return null;
    }
    const layers = this.children;
    const len = layers.length;
    const end = len - 1;
    let i = 0;
    let shape = null;

    for (i = end; i >= 0; i--) {
      shape = layers[i].getIntersection(pos);
      if (shape) {
        return shape;
      }
    }
    return null;
  }
}
